package com.hdax.dm.token;

import cn.hutool.crypto.asymmetric.RSA;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.Map;

@Component
public class TokenUtil {

    @Value("${jwt.rsa_private_key}")
    private String rsa_private_key;

    @Value("${jwt.rsa_public_key}")
    private String rsa_public_key;
    //token的有效时长
    @Value("${jwt.expire_time}")
    private String expire_time;

    /**
     * 生成新token
     */
    public String createToken(Map<String,String> params){
        //签发令牌 createToken
        RSA rsa = new RSA(rsa_private_key,null);
        Date date = new Date();
        JwtBuilder builder = Jwts.builder();
        builder.claim("nickName",params.get("nickName"));
        builder.claim("phone",params.get("phone"));
        builder.claim("realName",params.get("realName"));
        builder.setIssuedAt(date);//起始时间
        builder.setExpiration(new Date(date.getTime() + Long.parseLong(expire_time)));//过期时间 2h
        builder.setId(params.get("id"));
        builder.signWith(rsa.getPrivateKey(), SignatureAlgorithm.RS256);
        String token = builder.compact();
        return token;
    }


    @Value("${jwt.rsa_public_key}")
    private String publicKey;

    /**
     * 对token进行解密
     * @param token
     * @return
     */
    public String token(String token){
        if (token==null||token.equals("")){
            return "0";
        }
        RSA rsa = new RSA(null,publicKey);
        JwtParserBuilder parserBuilder = Jwts.parserBuilder();
        parserBuilder.setSigningKey(rsa.getPublicKey());
        JwtParser parser = parserBuilder.build();
        Claims claims = parser.parseClaimsJws(token).getBody();
        return claims.getId();
    }
}
